package com.sumainfor.pc.market.service;

import com.sumainfor.common.Constants;
import com.sumainfor.common.NiuYunToken;
import com.sumainfor.common.UnionPay.MapUtil;
import com.sumainfor.common.util.Arith;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.HtmlUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.CommunityMapper;
import com.sumainfor.pc.market.dao.FacilityMapper;
import com.sumainfor.pc.market.dao.HousingMapper;
import com.sumainfor.pc.market.dao.UtilsMapper;
import com.sumainfor.pc.market.feign.ZuulFeign.ZuulFeign;
import com.sumainfor.pc.market.util.HanyuPinyinHelper;
import com.sumainfor.pc.market.util.HanyuPinyinHelper.Type;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: zhlu
 * @Date: 2018/11/3 20:45
 * @Description:
 */
@Service
public class CommunityService implements Serializable{
    private ReentrantLock lock = new ReentrantLock(false);
    Logger log= LoggerFactory.getLogger(CommunityService.class);
    @Autowired
    CommunityMapper communityMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    FacilityMapper facilityMapper;

    @Autowired
    HousingMapper housingMapper;

    @Autowired
    ZuulFeign ZuulFeign;

    String UUID=null;
    /**
     * 功能描述:
     * 新增项目（小区）
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/3 20:47
     */
    public boolean AddCommunity(Map<String,Object> params){
        boolean result=false;
        /**
         * 加锁操作
         */
        lock.lock();
        try {
        	//初始化拼音工具类
        	HanyuPinyinHelper tool=new HanyuPinyinHelper();
        	//获取转换后的项目名称
        	String ComName=tool.getFirstSpell(params.get("ComName").toString(),Type.UPPERCASE);
        	//拼接项目名和路号
        	String ComNameRoad=ComName+params.get("Road").toString();
            try {
                params.put("by",ContextUtils.getUserId());//操作人
                params.put("ComId",ComNameRoad.toString());//项目编号等于项目名称加路号
                params.put("ComCod",ComName);//项目首字母编号
                params.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                //省市区复制
                Map<String,Object>citys=(Map<String,Object>)params.get("citys");
                params.putAll(citys);
                //新增小区
                communityMapper.AddCommunity(params);

                Map<String,Object>message=new HashMap<String,Object>();
                message.put("MeType","2");//市场部经理
                message.put("Title","待分配服务中心的新项目");
                message.put("Content", HtmlUtil.stringToHTML("注意！有新的项目创建 请及时审核并分配服务中心；",null,null));
                message.put("by",ContextUtils.getUserId());//操作人
                message.put("term","2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                //新增消息
                ZuulFeign.AddMessage(message);


                result=true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 功能描述: 
     * 根据小区名称和路号判断是否该小区重名
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/7 15:16
     */
    public int IfCommunity(Map<String,Object>params){
        int ifCom=communityMapper.IfCommunity(params);
        return ifCom;
    }

    /**
     * 功能描述:
     * 查询项目（小区）列表
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/8 14:41
     */
    public List<Map<String,Object>>getCommunityList(Map<String,Object>params){
        List<Map<String,Object>>getCommunityList=communityMapper.getCommunityList(params);
        for(Map<String,Object> map: getCommunityList){
            if(!FieldCheckUtil.isMapFieldNotNull(map,new String[]{"ComImg"})){
                map.put("ComImg",null);
            }else{
                map.put("ComImg", NiuYunToken.publicQiniuUrl+map.get("ComImg"));
            }

            //总数
            Map<String,Object> RentOutCount=housingMapper.getComIdByRentOut(new HashMap<String,Object>(){{
                put("ComId",map.get("ComId"));
            }});
            //已租房间数
            Map<String,Object> AlreadyTaken=housingMapper.getComIdByAlreadyTaken(new HashMap<String,Object>(){{
                put("ComId",map.get("ComId"));
            }});

            Double readyTaken;
            //不等空
            if(FieldCheckUtil.isMapFieldNotNull(AlreadyTaken,new String[]{"AlreadyTaken"})){
                readyTaken=Double.valueOf(AlreadyTaken.get("AlreadyTaken").toString());
                //总数不等于空
                if(FieldCheckUtil.isMapFieldNotNull(RentOutCount,new String[]{"RentOutCount"})){
                    Double RentCount=Double.valueOf(RentOutCount.get("RentOutCount").toString());
                    map.put("RentOut", Arith.mul(Arith.div(readyTaken,RentCount,2),100.00));//出租率
                }else{
                    map.put("RentOut",0);//出租率
                }
            }else{
                map.put("RentOut",0);//出租率
            }
            Double MeanCollectRent=communityMapper.getComIdByMeanCollectRent(new HashMap<String,Object>(){{
                put("ComId",map.get("ComId"));
            }});
            map.put("MeanCollectRent",MeanCollectRent);//平均收租

            Double MeanRentOut=communityMapper.getComIdByMeanRentOut(new HashMap<String,Object>(){{
                put("ComId",map.get("ComId"));
            }});
            map.put("MeanRentOut",MeanRentOut);//平均出租
        }
        return getCommunityList;
    }

    /**
     * 功能描述:
     * 查询项目（小区）列表数量
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/8 14:42
     */
    public int getCommunityListCount(Map<String,Object>params){
        int getCommunityListCount=communityMapper.getCommunityListCount(params);
        return getCommunityListCount;
    }

    /**
     * 功能描述:
     * 根据项目编号获取项目
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/8 18:43
     */
    public Map<String,Object>getCommunity(Map<String,Object>params){
        Map<String,Object>getCommunity=communityMapper.getCommunity(params);
        if(!FieldCheckUtil.isMapFieldNotNull(getCommunity,new String[]{"Facility"})){
            //设备数组
            List<Map<String,Object>>getFacilityList=facilityMapper.getFacilityList();
            for(Map<String,Object> map:getFacilityList){
                map.put("isbord",false);
                map.put("FaUrl", NiuYunToken.publicQiniuUrl+map.get("FaUrl"));
            }
            getCommunity.put("Facility",getFacilityList);
        }else{
            String[] Facility=getCommunity.get("Facility").toString().split(",");
            //设备数组
            List<Map<String,Object>>getFacilityList=facilityMapper.getFacilityList();
            for(Map<String,Object> map:getFacilityList){
                if(Arrays.asList(Facility).contains(map.get("FaId"))){
                    map.put("isbord",true);
                }else{
                    map.put("isbord",false);
                }
                map.put("FaUrl", NiuYunToken.publicQiniuUrl+map.get("FaUrl"));
            }
            getCommunity.put("Facility",getFacilityList);
        }
        List<String> State = new ArrayList<String>();
        State.add("2");
        State.add("3");
        State.add("4");
        State.add("5");
        State.add("6");
        State.add("7");

        Map<String,Object>Housing=housingMapper.getHousingReceivedCount(new HashMap<String,Object>(){{
            put("ComId",getCommunity.get("ComId"));
            put("State",State);
        }});
        getCommunity.put("Received",Housing.get("Received"));//已收
        getCommunity.put("SplitNumber",Housing.get("SplitNumber"));//拆分

        //总数
        Map<String,Object> RentOutCount=housingMapper.getComIdByRentOut(params);
        //已租房间数
        Map<String,Object> AlreadyTaken=housingMapper.getComIdByAlreadyTaken(params);

        Double readyTaken;
        //不等空
        if(FieldCheckUtil.isMapFieldNotNull(AlreadyTaken,new String[]{"AlreadyTaken"})){
            readyTaken=Double.valueOf(AlreadyTaken.get("AlreadyTaken").toString());
            getCommunity.put("AlreadyTaken",AlreadyTaken.get("AlreadyTaken"));//已租
            //总数不等于空
            if(FieldCheckUtil.isMapFieldNotNull(RentOutCount,new String[]{"RentOutCount"})){
                Double RentCount=Double.valueOf(RentOutCount.get("RentOutCount").toString());
                getCommunity.put("RentOut", Arith.mul(Arith.div(readyTaken,RentCount),100.00));//出租率
            }else{
                getCommunity.put("RentOut",0);//出租率
            }
        }else{
            getCommunity.put("AlreadyTaken",0);//已租
            getCommunity.put("RentOut",0);//出租率
        }
        Double MeanCollectRent=communityMapper.getComIdByMeanCollectRent(params);
        getCommunity.put("MeanCollectRent",MeanCollectRent);//平均收租

        return getCommunity;
    }

    /**
     * 功能描述:
     * 根据项目编号修改项目设备
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/9 11:39
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommunity(Map<String,Object>params){
        boolean result=false;
        params.put("by",ContextUtils.getUserId());//操作人
        params.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
        params.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonUpdateParms(params);
//        List<String> Facility = (List<String>) params.get("Facility");
        List<Map<String, Object>> Facility = (List<Map<String, Object>>) params.get("Facility");
        StringBuffer Fac = new StringBuffer();
        String facility = null;
        if (Facility != null && Facility.size() > 0) {
            for (Map<String, Object> map : Facility) {
                if(map.get("isbord").equals(true)){
                    Fac.append(map.get("FaId")).append(",");
                }
            }
            if(Fac.length()>0) {
                Fac.deleteCharAt(Fac.length() - 1);
            }
            facility = Fac.toString();
        }
        params.put("Facility", facility);
        try {
            communityMapper.updateCommunity(params);
            result=true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 功能描述:
     * 根据省市区街道获取项目编号列表
     * @Author zhlu
     * @Description //TODO
     * @Date 2018/11/11 11:26
     */
    public List<Map<String,Object>>SelectCommunityList(Map<String,Object>params){
        List<Map<String,Object>>SelectCommunityList=communityMapper.SelectCommunityList(params);
        return SelectCommunityList;
    }

    /**
     * 功能描述: 
     * 获取项目总数
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/4/13 16:03
     */
    public Integer getCommunityCount(){
        Integer getCommunityCount=communityMapper.getCommunityCount();
        return getCommunityCount;
    }

    /**
     * 功能描述:
     * 根据服务中心编号获取所有项目列表
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/6/20 19:15
     */
    public List<Map<String,Object>>getDepIdByCommunityList(Map<String,Object>params){
        return communityMapper.getDepIdByCommunityList(params);
    }
}
